package q93_restoreIpAddresses;

import java.util.ArrayList;
import java.util.List;


/**
 * 未完成 ——> 递归写法
 */
public class Solution_1 {
    public static void main(String[] args) {
        System.out.println("123456".substring(5,6));
        System.out.println(new Solution_1().restoreIpAddresses("101023"));
    }
    private List<String> res = new ArrayList<String>();
    private List<String> bin = new ArrayList<>();
    public List<String> restoreIpAddresses(String s) {
        if (s.length() < 4 || s.length() > 12){
            return res;
        }
        dfs(s, 0);
        return res;
    }

    void dfs(String s, int startIndex){
        // 这里的判断为了提高时间效率，直接在size为3的时候判断剩下的字符串即可
        if(bin.size() == 3) {
            if (isIP(s, startIndex, s.length() - 1)){
                String temp = "";
                for (String s1 : bin) {
                    temp += s1 + ".";
                }
                temp += s.substring(startIndex, s.length());
                res.add(temp);
            }
            return;
        }

        for(int i = startIndex;i < s.length();i++) {
            if(isIP(s, startIndex, i)){
                bin.add(s.substring(startIndex, i + 1));
                dfs(s, i + 1);
                bin.remove(bin.size() - 1);
            }
        }
    }

    private boolean isIP(String s, int startIndex, int i) {
        if (i - startIndex >= 3) {
            return false;
        }

        if (s.charAt(startIndex) == '0' && (i == startIndex)){
            return true;
        }
        if (s.charAt(startIndex) == '0' && (i != startIndex)) {
            return false;
        }
        if (Integer.parseInt(s.substring(startIndex, i + 1)) <= 255){
            return true;
        }
        return false;
    }
}
